package com.echo.aichat.ai.agent;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Agent
@Description("获取并分析微博实时热搜榜")
public class WeiboHotSearchAgent extends AbstractAgent<WeiboHotSearchAgent.Request, String> {
    private final String SYSTEM = """
            你是一个社交媒体分析师，擅长分析微博热搜数据。
            请根据提供的热搜数据，分析热点趋势并总结关键信息。
            """;

    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;

    public WeiboHotSearchAgent(ChatModel chatModel, HttpClient httpClient, ObjectMapper objectMapper) {
        super(chatModel);
        this.httpClient = httpClient;
        this.objectMapper = objectMapper;
    }

    @Override
    public String apply(Request request) {
        try {
            // 发送HTTP请求获取微博热搜数据
            HttpRequest httpRequest = HttpRequest.newBuilder()
                    .uri(URI.create("https://weibo.com/ajax/side/hotSearch"))
                    .header("User-Agent", "Mozilla/5.0 (compatible; MyBot/1.0)")
                    .GET()
                    .build();

            HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

            // 解析JSON数据
            WeiboResponse weiboResponse = objectMapper.readValue(response.body(), WeiboResponse.class);

            // 提取并处理数据
            List<HotItem> hotItems = weiboResponse.data().realtime().stream()
                    .sorted(Comparator.comparingInt(HotItem::num).reversed()) // 按热度降序排序
                    .collect(Collectors.toList());

            // 构建分析提示
            StringBuilder dataPrompt = new StringBuilder("当前微博热搜TOP10：\n");
            hotItems.stream().limit(10).forEach(item ->
                    dataPrompt.append(String.format("- %s (热度: %d)\n", item.word(), item.num()))
            );

            // 获取AI分析结果
            return getChatClient()
                    .prompt()
                    .system(SYSTEM)
                    .user(dataPrompt + "\n请分析上述热搜数据：")
                    .call()
                    .content();

        } catch (IOException | InterruptedException e) {
            return "获取微博热搜数据失败，请稍后再试。错误信息：" + e.getMessage();
        }
    }

    public record Request(
            @JsonProperty(required = true)
            @JsonPropertyDescription("触发热搜分析的请求内容") String query) {
    }

    // DTO类
    @JsonIgnoreProperties(ignoreUnknown = true)
    public record WeiboResponse(
            @JsonProperty("ok") int ok,
            @JsonProperty("data") HotSearchData data) {
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public record HotSearchData(
            @JsonProperty("realtime") List<HotItem> realtime) {
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public record HotItem(
            @JsonProperty("word") String word,
            @JsonProperty("num") int num) {
    }
}